package com.example.user.gridview;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class GridViewActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gridview);
        setTitle("网络视图");
        GridView gv = (GridView) findViewById(R.id.grid_view);
        gv.setAdapter(new ImageAdapter(this));
    }

    public class ImageAdapter extends BaseAdapter{
        //定义Context
        private Context mContext;

        public ImageAdapter(Context c){
            mContext = c;
        }
        //加图片 定义整型数组（图片资源）
        private Integer[] mThumbIds = {
                R.drawable.gridview_00,R.drawable.gridview_00,R.drawable.gridview_00,R.drawable.gridview_00,
                R.drawable.gridview_00,R.drawable.gridview_00,R.drawable.gridview_00,R.drawable.gridview_00,
                R.drawable.gridview_00,R.drawable.gridview_00,R.drawable.gridview_00,R.drawable.gridview_00
        };
        //获取图片数
        public int getCount(){
            return mThumbIds.length;
        }
        //获取图片在库的位置
        public Object getItem(int arg0){
            return null;
        }

        @Override
        //获取图片ID
        public long getItemId(int arg0){
            return 0;
        }

        @Override
        public View getView(int position,View convertView,ViewGroup parent){
            ImageView imageView;
            if(convertView == null){
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(85,85));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(8,8,8,8);//left,top,right,bottom
            }else {
                imageView = (ImageView) convertView;
            }
            imageView.setImageResource(mThumbIds[position]);
            return imageView;
        }
    }
}
